#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : zaniu(zzaniu@126.com)
# @Time   : 2021/6/24 22:52 
# @Desc   :
# 
#                   _ooOoo_
#                  o8888888o
#                  88" . "88
#                  (| -_- |)
#                  O\  =  /O
#               ____/`---'\____
#             .'  \\|     |//  `.
#            /  \\|||  :  |||//  \
#           /  _||||| -:- |||||-  \
#           |   | \\\  -  /// |   |
#           | \_|  ''\---/''  |   |
#           \  .-\__  `-`  ___/-. /
#         ___`. .'  /--.--\  `. . __
#      ."" '<  `.___\_<|>_/___.'  >'"".
#     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
#     \  \ `-.   \_ __\ /__ _/   .-` /  /
# =====`-.____`-.___\_____/___.-`____.-'=====
#                   `=---='
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#             佛祖保佑       永无BUG
#
import requests
import consul

header = {
    "Content-Type": "application/json"
}


def _register(name: str, tags: list, address: str, port: int, server_id: str = "", check_flag: bool = True):
    if not server_id: server_id = name
    url = "http://172.18.2.249:8500/v1/agent/service/register"
    res = requests.put(url, headers=header, json={
        "Name": name,
        "ID": server_id,
        "Tags": tags,
        "Address": address,
        "Port": port,
        "Check": {
            "HTTP": f"http://{address}:{port}/health",
            "Timeout": "5s",
            "Interval": "5s",
            "DeregisterCriticalServiceAfter": "5s",
        }
    })
    if res.status_code == 200:
        print("注册成功")
    else:
        print("注册失败")
        print(res.text)


def deregister(server_id: str):
    url = f"http://172.18.2.249:8500/v1/agent/service/deregister/{server_id}"
    res = requests.put(url, headers=header)
    if res.status_code == 200:
        print("注销成功")
    else:
        print("注销失败")


def get_service(server_id: str):
    # url = f"http://172.18.2.249:8500/v1/agent/service/{server_id}"
    url = f"http://172.18.2.249:8500/v1/agent/health/service/name/{server_id}"
    res = requests.get(url, headers=header)
    if res.status_code == 200:
        print(res.text)
    else:
        print(f"获取失败, {res.text}")


def register(name: str, tags: list, host: str, port: int):
    consul_instance = consul.Consul("172.18.2.249", 8500)
    consul_instance.agent.service.register(
            name,
            name,
            host,
            port,
            tags,
            # 健康检查ip端口，检查时间：5,超时时间：30，注销时间：30s
            check=consul.Check().tcp(host, port, "5s", "5s", "5s"))


def register_grpc(name: str, tags: list, address: str, port: int, server_id: str = "", check_flag: bool = True):
    if not server_id: server_id = name
    url = "http://172.18.2.249:8500/v1/agent/service/register"
    res = requests.put(url, headers=header, json={
        "Name": name,
        "ID": server_id,
        "Tags": tags,
        "Address": address,
        "Port": port,
        "Check": {
            "GRPC": f"{address}:{port}",
            "GRPCUseTLS": False,
            "Timeout": "5s",
            "Interval": "5s",
            "DeregisterCriticalServiceAfter": "15s",
        }
    })
    if res.status_code == 200:
        print("注册成功")
    else:
        print("注册失败")
        print(res.text)


if __name__ == '__main__':
    # deregister("gmb")
    # register("gmb", ["gmb", "kucun", "nems"], "172.18.2.184", 8089)
    # _register("gmb", ["gmb", "kucun", "nems"], "172.18.2.184", 8089)
    # _register("gmb", ["gmb", "kucun", "nems"], "172.18.2.184", 8088, server_id="gmb2")
    get_service("gmb")
